import threading
import hashlib
import time
from Crypto.Hash import SHA256
import emoji


# 利用多线程库threading，可以并行处理多个挖矿任务
def threaded_mining(difficulty, thread_id):
    x = 0
    while True:
        x += 1
        string = 'hxy and wzw'
        start_string = str(x) + str(thread_id)
        combine_string = start_string + string
        h = hashlib.sha256()
        h.update(combine_string.encode('utf-8'))
        gold_hash = h.hexdigest()

        if gold_hash[0:difficulty] == '0' * difficulty:
            print(f'线程 {thread_id} 挖矿成功！哈希值: {gold_hash}')
            break


def start_threaded_mining(difficulty, num_threads):
    threads = []
    # 每个线程都进行挖矿
    for i in range(num_threads):
        thread = threading.Thread(target=threaded_mining, args=(difficulty, i+1))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()


# 使用更高效的哈希函数SHA256,以提高哈希计算速度
def optimized_hash(combine_string):
    h = SHA256.new()
    h.update(combine_string.encode('utf-8'))
    return h.hexdigest()


# 根据当前网络算力和挖矿速度，动态调整难度系数
def adjust_difficulty(current_difficulty, target_time, actual_time):
    # 当挖矿实际所花的时间小于设置的目标时间，就增加一个难度等级
    if actual_time < target_time:
        return current_difficulty + 1
    # 当挖矿实际所花的时间大于设置的目标时间，就减少一个难度等级，但最低等级是1
    elif actual_time > target_time:
        return max(1, current_difficulty - 1)
    return current_difficulty


# 测试算法
def main():
    print("您好，欢迎使用挖矿算法！")
    str_emoji = ":sparkling_heart:" * 3
    print(emoji.emojize(str_emoji, language='alias', variant="emoji_type"))

    print("请输入挖矿的初始难度系数(数字)：")
    initial_difficulty = int(input())
    print("请输入线程数(数字)：")
    num_threads = int(input())
    # 目标挖矿时间（秒）
    print("请设置目标挖矿时间(数字)：")
    target_time = int(input())

    print("请输入挖矿次数(数字)：")
    count = int(input())
    print("挖矿即将开始！")
    str_emoji2 = ':smiling_face_with_hearts:' * 3
    print(emoji.emojize(str_emoji2, language='alias', variant="emoji_type"))

    while True:
        if count != 0:
            print("挖矿进行中，请稍等：")
            # 引入emoji库中的表情，让输出更加人性化
            str_emoji2 = ':rose:' * 3
            # 打印表情
            print(emoji.emojize(str_emoji2, language='alias', variant="emoji_type"))

            # 记录挖矿开始时间
            start_time = time.time()
            start_threaded_mining(initial_difficulty, num_threads)
            # 记录挖矿结束时间
            end_time = time.time()
            # 计算挖矿所花时间
            actual_time = end_time - start_time
            # 根据实际调整难度
            initial_difficulty = adjust_difficulty(initial_difficulty, target_time, actual_time)
            print(f'当前难度: {initial_difficulty}, 实际用时: {actual_time}秒')
            # 每进行一次，挖矿次数减1
            count -= 1
        else:
            print("挖矿结束，欢迎下次使用！")
            str_emoji2 = ':heart:' * 3
            print(emoji.emojize(str_emoji2, language='alias', variant="emoji_type"))
            break


if __name__ == '__main__':
    main()